import {messages} from "share/common";
import React, { Component, PropTypes } from 'react';
import {connect} from 'react-redux'
import 'styles/components/inline-description.scss'
import ReactDOM from "react-dom";

class InlineDescription extends Component {

  state = {
    showExpandBtn: false,
    expanded: false,
    defaultHeight: 0
  };
  descriptionRef = null;

  componentDidMount = () => {
    let dom = ReactDOM.findDOMNode(this.descriptionRef);
    let pos = dom.getBoundingClientRect();
    if(pos.height > this.props.defaultRows * this.props.lineHeight) {
      this.setState({ showExpandBtn: true, defaultHeight: pos.height })
    } else {
      this.setState({ defaultHeight: pos.height })
    }
  };

  handleExpandDescription = () => {
    const { expanded } = this.state;
    this.setState({ expanded: !expanded });
  };


  render() {
    const { title, content, hideText, showText, defaultRows, lineHeight } = this.props;
    const { defaultHeight, showExpandBtn, expanded } = this.state;
    let maxHeight = defaultRows * lineHeight;

    return (
      <div className='inline-description'>
        {title && <div className='inline-description-title'>{title}</div>}
        <div
          className='inline-description-content'
          style={{ lineHeight: `${lineHeight}px`, height: (showExpandBtn && !expanded) ? maxHeight : defaultHeight }}
        >
          <div ref={ref => this.descriptionRef = ref}>{content}</div>
          {showExpandBtn && (
            <div onClick={this.handleExpandDescription} className='toggle-btn'>
              {expanded ? hideText : showText}
            </div>
          )}
        </div>
      </div>
    );
  }

  static propTypes = {

  };

  static defaultProps = {
    hideText: messages('common.fold')/*收起*/,
    showText: messages('common.all')/*全部*/,
    defaultRows: 3,
    lineHeight: 22
  };

}

function mapStateToProps(state) {
  return {
    language: state.main.language
  }
}

export default connect(mapStateToProps)(InlineDescription);
